package com.situ.mall.controller.front;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.situ.mall.VO.CartItemVO;
import com.situ.mall.VO.CartVO;
import com.situ.mall.common.ServerResponse;
import com.situ.mall.entity.Cart;
import com.situ.mall.entity.User;
import com.situ.mall.service.ICartService;
import com.situ.mall.service.IUserService;

@RequestMapping("/user")
@Controller
public class FrontUserController {

	private static final Integer CART_CHCKED = null;
	// 设置到cookie中购物车名字
	private final String CART_COOKIE = "cart_cookie";
	// 购物车选中状态
	private final Integer CART_CHECKED = 1;
	// 购物车未选中状态
	private final Integer CART_UNCHECKED = 0;

	@Autowired
	private IUserService userService;
	@Autowired
	private ICartService CartService;

	// 跳转到登录界面
	@RequestMapping("/getLoginPage.shtml")
	public String getLoginPage() {
		return "/login";
	}

	@RequestMapping("/login.shtml")
	@ResponseBody
	public ServerResponse login(HttpServletRequest request, String username, String password, HttpSession session) {
		ServerResponse response = userService.login(username, password);
		// 这个用户是存在的
		if (response.isSuccess()) {
			session.setAttribute("USER", response.getData());
		}
		// cookie 转化成 cartVO
		CartVO cartVO = getCartVOFromCookie(request);
		if (cartVO != null) {
			List<CartItemVO> cartItemVOList = cartVO.getCartItemVOList();
			// 用userId 查询 cart表中有没有订单
	   		User user = (User) response.getData();
			Integer userId = user.getId();
			//Cart cart = CartService.selectByUserId(userId);
			for (CartItemVO cartItemVO : cartItemVOList) {
				// 获取商品ID，数量，价格,选中状态
				Integer productId = cartItemVO.getProduct().getId();
				Integer amount = cartItemVO.getAmount();
				/* BigDecimal price = cartItemVO.getProduct().getPrice(); */
				Integer isChecked = cartItemVO.getIsChecked();
				Cart cart = CartService.selectByProductId(productId);
				if (cart == null) {
					// == null new一个新的出来
					Cart record = new Cart();
					record.setProductId(productId);
					record.setQuantity(amount);
					record.setChecked(isChecked);
					record.setUserId(userId);
					// 根据userID向cart表中插入这条数据(insert)
					CartService.insertSelective(record);
				} else {
					// 通过userID查出购物车中商品数量，然后进行更新
					Integer quantity = cart.getQuantity();
					quantity = quantity + amount;
					CartService.updateAmountByProductId(quantity);
				}
			}
		}
		
		return response;
	}

	@RequestMapping("/getUserPage")
	public String getUserPage() {

		return "/user/user_list";
	}

	@RequestMapping("/pageList")
	@ResponseBody
	public ServerResponse pageList(Integer page, Integer limit) {
		ServerResponse serverResponse = userService.pageList(page, limit);
		System.out.println(serverResponse);
		return serverResponse;
	}

	/**
	 * 将cookie中的购物车信息转化为cartVO 对象
	 */
	private CartVO getCartVOFromCookie(HttpServletRequest request) {
		CartVO cartVO = null;
		ObjectMapper objectMapper = new ObjectMapper();
		// 只有对象不为null进行转换
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
		// 将客户端中cookie拿出来?
		Cookie[] cookies = request.getCookies();
		if (null != cookies && cookies.length != 0) {
			for (Cookie cookie : cookies) {
				if (CART_COOKIE.equals(cookie.getName())) {
					// 找到了购物车中cookie的购物信息
					String value = cookie.getValue();
					// 将json字符串转换成java对象
					try {
						cartVO = objectMapper.readValue(value, CartVO.class);
					} catch (JsonParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (JsonMappingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
		}

		return cartVO;
	}
}
